/**
 * @Title:  AES.java
 * @Copyright (C) 2014-2015 by ywx.co.,ltd.All Rights Reserved.
 *  YWX CONFIDENTIAL AND TRADE SECRET
 * @author:  
 * @data:    
 */
package cn.chuxing.pl.common.util;

import org.apache.log4j.Logger;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密解密
 * 
 * */
public class AES {

	private static Logger log = Logger.getLogger(AES.class);

	static final String algorithmStr = "AES/ECB/PKCS5Padding";
	static final String iv = "abcdefghijklmnop";
	

	public static String decrypt(String content, String password){
		try{
//			byte[] input = content.getBytes();
			byte[] input = parseHexStr2Byte(content);
			byte[] retVal = decrypt(iv, password, input);
//			return parseByte2HexStr(retVal);
			return new String(retVal);
		}catch(Exception ex){
			log.error("decrypt error", ex);
		}
		return null;
	}
	
	public static String encrypt(String content, String password){
		try{
			byte[] retVal = encrypt(iv, password, content.getBytes());
			return parseByte2HexStr(retVal);
		}catch(Exception ex){
			log.error("encrypt error", ex);
		}
		return null;
	}
	
  public static byte[] decrypt(String iv, String password, byte[] input)
    throws Exception {
	  byte[] pwd = parseHexStr2Byte(password);
    SecretKeySpec key = new SecretKeySpec(pwd, "AES");
    
    Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    
    IvParameterSpec localIvParameterSpec = new IvParameterSpec(iv.getBytes());
    
    localCipher.init(2, key, localIvParameterSpec);
    
    return localCipher.doFinal(input);
  }

  public static byte[] encrypt(String iv, String password, byte[] input)
    throws Exception{
	  byte[] pwd = parseHexStr2Byte(password);
    SecretKeySpec localSecretKeySpec = new SecretKeySpec(pwd, "AES");
    Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec localIvParameterSpec = new IvParameterSpec(iv.getBytes());
    localCipher.init(1, localSecretKeySpec, localIvParameterSpec);
    return localCipher.doFinal(input);
  }
  
	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return
	 */
	private static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	private static byte[] parseHexStr2Byte(String hexStr) {
		if (hexStr.length() < 1)
			return null;
		byte[] result = new byte[hexStr.length() / 2];
		for (int i = 0; i < hexStr.length() / 2; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}

}
